<?php

namespace App\Http\Controllers\Mini;

use App\Http\Controllers\Controller;
use App\Models\Circle;
use App\Models\CircleLike;
use App\Models\CommentNotice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * Class CircleLikeController
 * @package App\Http\Controllers\Mini\Circle
 * 邻里圈动态点赞控制器
 */
class CircleLikeController extends Controller
{
    private $user_id;

    public function __construct()
    {
        $id = auth('user')->id();
        $this->user_id = $id;
    }

    /**
     * @param Request $request
     * @return array
     * 邻里圈消息 喜欢 / 取消喜欢
     */
    public function like(Request $request)
    {
        $user_id = $this->user_id;

        if (!$user_id) {
            return $this->error('请先登录');
        }

        $circle_id = $request->get('circle_id');

        if (!$circle_id) {
            return $this->error('参数错误');
        }

        //获取用户已经点赞过的动态
        $data = CircleLike::query()->where('user_id', $user_id)->value('circle_ids') ?? '[]';
        $data = json_decode($data, true);

        if (in_array($circle_id, $data)) {
            $msg = '取消成功';
            $key = array_search($circle_id, $data);
            unset($data[$key]);
        } else {
            //声明一个变量判断是否是点赞
            $state = true;
            //收藏成功
            $msg = '点赞成功';
            array_push($data, $circle_id);
        }
        $insert = ['circle_ids' => json_encode($data)];

        //查询发布动态的用户是谁
        $circle_user_id = Circle::query()->where('id', $circle_id)->value('user_id');

        DB::beginTransaction();
        try {
            if (isset($state)) {
                //如果通知的人是登录的人，那就不用通知了
                if ($circle_user_id != $user_id) {
                    //收藏
                    $create = [
                        'msg' => '赞了你的邻里圈动态',
                        'circle_id' => $circle_id, //邻里圈跳蚤市场商品ID
                        'user_id' => $circle_user_id, //被通知人ID
                        'from_user_id' => $user_id //来自谁的通知用户ID
                    ];
                    //记录通知
                    CommentNotice::query()->create($create);
                }

                Circle::query()->where('id', $circle_id)->increment('star');
            } else {
                Circle::query()->where('id', $circle_id)->decrement('star');
            }

            CircleLike::query()->updateOrInsert(['user_id' => $user_id], $insert);

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->error($exception->getMessage());
        }

        return $this->success([], $msg);
    }
}
